using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using OrderingSystem.Core.Entities;
using OrderingSystem.Infrastructure.Data;

namespace OrderingSystem.API.Controllers
{
    [ApiController]
    [Route("dingdanpeisong")]
    public class OrderDeliveryController : ControllerBase
    {
        private readonly ApplicationDbContext _context;

        public OrderDeliveryController(ApplicationDbContext context)
        {
            _context = context;
        }

        [HttpGet("page")]
        [AllowAnonymous]
        public async Task<IActionResult> GetDeliveryPage(
            [FromQuery] int page = 1,
            [FromQuery] int limit = 10,
            [FromQuery] string sort = "addtime",
            [FromQuery] string order = "desc",
            [FromQuery] string status = null)
        {
            try
            {
                var query = _context.OrderDeliveries.AsQueryable();

                // 筛选配送状态
                if (!string.IsNullOrEmpty(status))
                {
                    query = query.Where(o => o.peisongzhuangtai == status);
                }

                // 排序
                if (sort == "addtime")
                {
                    query = order == "desc"
                        ? query.OrderByDescending(o => o.addtime)
                        : query.OrderBy(o => o.addtime);
                }
                else if (sort == "id")
                {
                    query = order == "desc"
                        ? query.OrderByDescending(o => o.id)
                        : query.OrderBy(o => o.id);
                }

                // 获取总记录数
                var total = await query.CountAsync();

                // 获取分页数据
                var deliveries = await query
                    .Skip((page - 1) * limit)
                    .Take(limit)
                    .Select(o => new
                    {
                        id = o.id,
                        addtime = o.addtime,
                        dingdanbianhao = o.dingdanbianhao,
                        caipinmingcheng = o.caipinmingcheng,
                        caipinfenlei = o.caipinfenlei,
                        tupian = o.tupian,
                        shuliang = o.shuliang,
                        zongjine = o.zongjine,
                        peisongzhuangtai = o.peisongzhuangtai,
                        gengxinshijian = o.gengxinshijian,
                        yonghuming = o.yonghuming,
                        lianxidianhua = o.lianxidianhua,
                        sfsh = o.sfsh,
                        shhf = o.shhf,
                        userid = o.userid
                    })
                    .ToListAsync();

                return Ok(new
                {
                    code = 0,
                    data = new
                    {
                        total,
                        pageSize = limit,
                        totalPage = (int)Math.Ceiling((double)total / limit),
                        currPage = page,
                        list = deliveries
                    }
                });
            }
            catch (Exception ex)
            {
                Console.WriteLine($"获取订单配送分页数据时发生错误: {ex.Message}");
                Console.WriteLine($"异常堆栈: {ex.StackTrace}");
                return StatusCode(500, new { code = 500, msg = "服务器内部错误", error = ex.Message });
            }
        }

        [HttpGet("list")]
        [AllowAnonymous]
        public async Task<IActionResult> GetDeliveries([FromQuery] string status = null)
        {
            try
            {
                var query = _context.OrderDeliveries.AsQueryable();

                if (!string.IsNullOrEmpty(status))
                {
                    query = query.Where(o => o.peisongzhuangtai == status);
                }

                var deliveries = await query
                    .OrderByDescending(o => o.addtime)
                    .Select(o => new
                    {
                        id = o.id,
                        addtime = o.addtime,
                        dingdanbianhao = o.dingdanbianhao,
                        caipinmingcheng = o.caipinmingcheng,
                        caipinfenlei = o.caipinfenlei,
                        tupian = o.tupian,
                        shuliang = o.shuliang,
                        zongjine = o.zongjine,
                        peisongzhuangtai = o.peisongzhuangtai,
                        gengxinshijian = o.gengxinshijian,
                        yonghuming = o.yonghuming,
                        lianxidianhua = o.lianxidianhua,
                        sfsh = o.sfsh,
                        shhf = o.shhf,
                        userid = o.userid
                    })
                    .ToListAsync();

                return Ok(new { code = 0, data = deliveries });
            }
            catch (Exception ex)
            {
                Console.WriteLine($"获取订单配送列表时发生错误: {ex.Message}");
                Console.WriteLine($"异常堆栈: {ex.StackTrace}");
                return StatusCode(500, new { code = 500, msg = "服务器内部错误", error = ex.Message });
            }
        }

        [HttpGet("detail/{id}")]
        [AllowAnonymous]
        public async Task<IActionResult> GetDeliveryDetail(long id)
        {
            try
            {
                var delivery = await _context.OrderDeliveries
                    .Select(o => new
                    {
                        id = o.id,
                        addtime = o.addtime,
                        dingdanbianhao = o.dingdanbianhao,
                        caipinmingcheng = o.caipinmingcheng,
                        caipinfenlei = o.caipinfenlei,
                        tupian = o.tupian,
                        shuliang = o.shuliang,
                        zongjine = o.zongjine,
                        peisongzhuangtai = o.peisongzhuangtai,
                        gengxinshijian = o.gengxinshijian,
                        yonghuming = o.yonghuming,
                        lianxidianhua = o.lianxidianhua,
                        sfsh = o.sfsh,
                        shhf = o.shhf,
                        userid = o.userid
                    })
                    .FirstOrDefaultAsync(o => o.id == id);

                if (delivery == null)
                {
                    return NotFound(new { code = 404, msg = "配送订单不存在" });
                }

                return Ok(new { code = 0, data = delivery });
            }
            catch (Exception ex)
            {
                Console.WriteLine($"获取配送订单详情时发生错误: {ex.Message}");
                Console.WriteLine($"异常堆栈: {ex.StackTrace}");
                return StatusCode(500, new { code = 500, msg = "服务器内部错误", error = ex.Message });
            }
        }

        [HttpGet("info/{id}")]
        [AllowAnonymous]
        public async Task<IActionResult> GetDeliveryInfo(long id)
        {
            return await GetDeliveryDetail(id);
        }
    }
} 